package com.jsy.mqhelper.charlotterpc.register;

import java.lang.reflect.Method;

import javax.annotation.PostConstruct;

import com.jsy.mqhelper.charlotterpc.annotation.CharlotteService;
import com.jsy.mqhelper.common.core.LocalRegistry;
import com.jsy.mqhelper.common.core.MetaFunction;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;

import static com.jsy.mqhelper.common.constant.Constants.MQ_HELPER;

/**
 * @author: SongyangJi
 * @description:
 * @since: 2021/9/25
 */
@Slf4j(topic = MQ_HELPER)
public class LocalRegisterHandler implements BeanPostProcessor {

    LocalRegistry localRegistry;

    public LocalRegisterHandler(LocalRegistry localRegistry) {
        this.localRegistry = localRegistry;
    }

    @SneakyThrows
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {

        Class<?> beanClass = bean.getClass();

        if (beanClass.isAnnotationPresent(CharlotteService.class)) {
            log.debug("rpc service bean={}", bean);
            log.debug("rpc service class={}", bean.getClass());
            Class<?>[] interfaces = beanClass.getInterfaces();
            for (Class<?> interfaceClass : interfaces) {
                log.debug("  -  interfaceClass={}, Name={}", interfaceClass, interfaceClass.getName());
                Method[] declaredMethods = interfaceClass.getDeclaredMethods();
                for (Method method : declaredMethods) {
                    MetaFunction metaFunction = new MetaFunction(method, bean);
                    localRegistry.register(metaFunction);
                    log.debug("  -    -  metaFunction={}", metaFunction);
                }

            }
        }
        return bean;
    }

    @PostConstruct
    public void init() {
        log.info("LocalRegisterHandler bean create successfully.");
    }

}
